package com.wei.ssm.controller;

import com.wei.ssm.domain.Role;
import com.wei.ssm.domain.UserInfo;
import com.wei.ssm.service.IUserService;
import com.wei.utils.BCryptPasswordEncoderUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

/**
 * @author wei
 */
@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private IUserService iUserService;

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    /*

     */
    @RequestMapping("/addRoleToUser.do")
    public String addRoleToUser(@RequestParam(name = "userId",required = true) int userId,@RequestParam(value = "ids",required = true) int[] ids){
        iUserService.addRoleToUser(userId,ids);
        return "redirect:/user/findAll.do";
    }
    /**
        查找还有哪些可以添加的角色
     */

    @RequestMapping("/findUserByIdAndAllRole.do")
    public ModelAndView findUserByIdAndAllRole(@RequestParam(name = "id",required = true) int id){

        ModelAndView modelAndView = new ModelAndView();
        //找到这个用户的信息
        UserInfo userInfo = iUserService.findById(id);
        //找到这个其他的角色
        List<Role> roleList = iUserService.findUserByIdAndAllRole(id);
        modelAndView.addObject("user",userInfo);
        modelAndView.addObject("roleList",roleList);
        iUserService.findUserByIdAndAllRole(id);
        modelAndView.setViewName("user-role-add");
        return modelAndView;
    }

    @RequestMapping("/findById.do")
    public ModelAndView findById(int id){
        ModelAndView modelAndView = new ModelAndView();
        UserInfo userInfo = iUserService.findById(id);
        modelAndView.addObject("user",userInfo);
        modelAndView.setViewName("user-show");
        return modelAndView;
    }

    @RequestMapping("save.do")
    public String saveUser(UserInfo user){
        //进行用户的保存，通过加密方式，把密码放入数据库中
//        user.setPassword(BCryptPasswordEncoderUtils.getPassword(user.getPassword()));
        user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
        iUserService.save(user);
        return "redirect:/user/findAll.do";
    }


    @RequestMapping("/findAll.do")
    public ModelAndView findAll() throws Exception {
        ModelAndView modelAndView = new ModelAndView();
        List<UserInfo> userList = iUserService.findAll();
        modelAndView.addObject("userList",userList);
        modelAndView.setViewName("user-list");
        return modelAndView;
    }
}
